import { Card, } from "antd";
import { EChartsCoreOption } from "echarts";
import './index.scss'
import dayjs from "dayjs";
import { StatisticParams } from "@/types/statistics";
import { getOrdersStatisticsApi, getTopApi, getTurnoverStatisticsApi, getUserStatisticsApi } from "@/api/statistics";
import { graphic } from "echarts/core";
import axios from "axios";
import { useUserStore } from "@/stores/user";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { modal } from "@/utils/AntdGlobal";

export function Component() {
  let [turnoverOption, setTurnoverOption] = useState<EChartsCoreOption>({})
  let [userOption, setUserOption] = useState<EChartsCoreOption>({})
  let [orderOption, setOrderOption] = useState<EChartsCoreOption>({})
  let [topOption, setToprOption] = useState<EChartsCoreOption>({})
  useEffect(() => {
    // 获取当前时间
    const end = dayjs(+new Date()).format('YYYY-MM-DD')
    // 获取30天前的时间
    const begin = dayjs(+new Date() - 30 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
    const params = {
      begin, end
    }
    // 获取营业额统计
    getTurnover(params)
    // 获取用户统计
    getUser(params)
    // 获取订单统计
    getOrder(params)
    // 获取前10
    getTop(params)
  }, [])
  // 获取前10
  const getTop = async (params: StatisticParams) => {
    const res = await getTopApi(params)
    setToprOption({
      ...topOption,
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#fff', //背景颜色（此时为默认色）
        borderRadius: 2, //边框圆角
        textStyle: {
          color: '#333', //字体颜色
          fontSize: 12, //字体大小
          fontWeight: 300,
        },
      },
      grid: {
        top: '-10px',
        left: '0',
        right: '0',
        bottom: '0',
        containLabel: true,
      },
      xAxis: {
        show: false,
      },
      yAxis: {
        //   隐藏y轴坐标轴
        axisLine: {
          show: false,
        },
        // 隐藏y轴刻度线
        axisTick: {
          show: false,
          alignWithLabel: true,
        },
        type: 'category',
        // interval: 100,
        nameTextStyle: {
          color: '#666',
          fontSize: '12px',
        },
        data: res.data.nameList.split(',').reverse(),
      },
      series: [
        {
          data: res.data.numberList.split(',').reverse(),
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: '#F3F4F7',
          },
          barWidth: 20,
          barGap: '80%' /*多个并排柱子设置柱子之间的间距*/,
          barCategoryGap: '80%' /*多个并排柱子设置柱子之间的间距*/,
          label: {
            //内容样式
            show: true,
            formatter: '{@score}',
            color: '#333',
            // position: "insideLeft", //内部左对齐
            position: ['8', '5'], //自定义位置第一个参数为x轴方向，第二个参数为y轴方向，左上角为起点，向右向下为正数，向上向左为负数
          },
          itemStyle: {
            borderRadius: 30,
            // borderRadius : [0, 10, 10, 0], // 圆角
            color: new graphic.LinearGradient( // 渐变色
              1,
              0,
              0,
              0, // 渐变色的起止位置, 右/下/左/上
              [
                // offset 位置
                { offset: 0, color: '#0e8b8d' },
                { offset: 1, color: '#e7f3f4' },
              ]
            ),
          },
        },
      ],
    })
  }
  // 获取订单统计
  const getOrder = async (params: StatisticParams) => {
    const res = await getOrdersStatisticsApi(params)
    setOrderOption({
      ...orderOption,
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['订单总数(个)', '有效订单(个)']
      },
      xAxis: {
        type: 'category',
        data: res.data.dateList.split(','),
        axisTick: {
          show: false // 不显示坐标轴刻度线
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '订单总数(个)',
          barWidth: 20,
          data: res.data.orderCountList.split(','),
          type: 'bar',
          itemStyle: {
            color: '#0e8b8d', // 改变折线点的颜色
          },
        },
        {
          name: '有效订单(个)',
          barWidth: 20,
          data: res.data.validOrderCountList.split(','),
          type: 'bar',
          itemStyle: {
            color: '#fd7f7f', // 改变折线点的颜色
          },
        }
      ]
    })
  }
  // 获取用户统计
  const getUser = async (params: StatisticParams) => {
    const res = await getUserStatisticsApi(params)
    setUserOption({
      ...userOption,
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['用户总量(个)', '新增用户(个)']
      },
      xAxis: {
        type: 'category',
        data: res.data.dateList.split(','),
        axisTick: {
          show: false // 不显示坐标轴刻度线
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '用户总量(个)',
          data: res.data.totalUserList.split(','),
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#0e8b8d', // 改变折线点的颜色
          },
          lineStyle: {
            color: '#0e8b8d'
          }
        },
        {
          name: '新增用户(个)',
          data: res.data.newUserList.split(','),
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#fd7f7f', // 改变折线点的颜色
          },
          lineStyle: {
            color: '#fd7f7f'
          }
        }
      ]
    })
  }
  // 获取营业额统计
  const getTurnover = async (params: StatisticParams) => {
    const res = await getTurnoverStatisticsApi(params)
    setTurnoverOption({
      ...turnoverOption,
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['营业额(元)']
      },
      xAxis: {
        type: 'category',
        data: res.data.dateList.split(','),
        axisTick: {
          show: false // 不显示坐标轴刻度线
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '营业额(元)',
          data: res.data.turnoverList.split(','),
          type: 'line',
          itemStyle: {
            color: '#0e8b8d', // 改变折线点的颜色
          },
          lineStyle: {
            color: '#0e8b8d'
          }
        }
      ]
    })
  }
  // 导出数据
  const handleBinaryExport = async () => {
    modal.confirm({
      title: '导出数据',
      icon: <ExclamationCircleOutlined />,
      content: '确认要导出30天的数据嘛?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const token = useUserStore.getState().token
        const response = await axios.request({
          url: '/api/admin/report/export',
          method: 'get',
          headers: {
            token
          },
          responseType: 'blob',
        });
        const blob = new Blob([response.data], { type: 'application/json' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '运营数据报表模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        message.success('导出成功')
      }
    });
  };
  return (
    <div className="statistics">
      {/* 查询 */}
      <Card title="营业额统计"
        extra={<div className="color-#0e8b8d cursor-pointer" onClick={handleBinaryExport}>导出数据</div>}
        className="mb-4 oddNumber" size="small">
        <Echarts option={turnoverOption} width={"100%"} height={"100%"} />
      </Card>
      <Card title="用户统计" className="mb-4 evenNumber" size="small">
        <Echarts option={userOption} width={"100%"} height={"100%"} />
      </Card>
      <Card title="订单统计" className="mb-4 oddNumber" size="small">
        <Echarts option={orderOption} width={"100%"} height={"100%"} />
      </Card>
      <Card title="销量排名TOP8" className="mb-4 evenNumber" size="small">
        <Echarts option={topOption} width={"100%"} height={"100%"} />
      </Card>
    </div >
  )
}